package com.example.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.dto.DishDto;
import com.example.entity.Category;
import com.example.entity.Dish;
import com.example.entity.DishFlavor;
import com.example.mapper.DishMapper;
import com.example.service.CategoryService;
import com.example.service.DishFlavorService;
import com.example.service.DishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.util.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 服务实现类
 * </p>
 *
 * @author bd
 * @since 2023-05-27
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    public Page<DishDto> ListDishDto(Page<Dish> pageInfo, Page<DishDto> pageDishDto) {
        BeanUtils.copyProperties(pageInfo,pageDishDto,"records");
        List<Dish> records = pageInfo.getRecords();//获取原有的records 重新装配
        List<DishDto> Dtocollect = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);//别忘了把其他属性都拷贝进来。
            Category  category = categoryService.getById(item.getCategoryId());
            if(category!=null) {
                dishDto.setCategoryName(category.getName());
            }
            else{
                dishDto.setCategoryName("暂无");
            }
            return dishDto;
        }).collect(Collectors.toList());
        //Dtocollect是重新装配的records
        pageDishDto.setRecords(Dtocollect);
        return pageDishDto;
    }

    @Override
    public boolean addnewDish(DishDto dishDto) {
        //插入两张表
        //第一张插入Dish
        boolean dishsave = this.save(dishDto);
        if(dishsave)
        {
            //如何拿到刚插入的dish的ID
            //dishDto中插入之后还会保有id
            List<DishFlavor> flavors = dishDto.getFlavors();
            for(DishFlavor dishFlavor:flavors)
            {
                dishFlavor.setDishId(dishDto.getId());
            }
            dishFlavorService.saveBatch(flavors);
            return true;
        }
        else {
            return false;
        }
    }
}
